package com.fighYo.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fighYo.edu.entity.EduChapter;
import com.fighYo.edu.entity.EduVideo;
import com.fighYo.edu.entity.vo.ChapterVo;
import com.fighYo.edu.entity.vo.VideoVo;
import com.fighYo.edu.mapper.EduChapterMapper;
import com.fighYo.edu.service.EduChapterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fighYo.edu.service.EduVideoService;
import com.fighYo.servicebase.config.handler.GuliException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author fighYo
 * @since 2021-08-24
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {

    @Autowired
    private EduVideoService eduVideoService;

    @Override
    public List<ChapterVo> getChapterByCourseId(String courseId) {
        QueryWrapper<EduChapter> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("course_id", courseId);
        wrapper1.orderByAsc("sort", "id");
        List<EduChapter> eduChapters = baseMapper.selectList(wrapper1);
//        if(eduChapters == null) {
//            throw new GuliException(20001, "该课程没有章节");
//        }
        ArrayList<ChapterVo> chapterVos = new ArrayList<>();
        for(EduChapter eduChapter: eduChapters) {
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(eduChapter, chapterVo);
            QueryWrapper<EduVideo> wrapper2 = new QueryWrapper<>();
            wrapper2.eq("chapter_id", eduChapter.getId());
            wrapper2.orderByAsc("sort", "id");
            List<EduVideo> eduVideos = eduVideoService.list(wrapper2);
            for(EduVideo eduVideo: eduVideos) {
                VideoVo videoVo = new VideoVo();
                BeanUtils.copyProperties(eduVideo, videoVo);
                chapterVo.getChildren().add(videoVo);
            }
            chapterVos.add(chapterVo);
        }
        return chapterVos;
    }

    @Override
    public boolean removeChapterById(String id) {
        QueryWrapper<EduVideo> wrapper = new QueryWrapper<>();
        wrapper.eq("chapter_id", id);
        int count = eduVideoService.count(wrapper);
        if(count > 0) {
            throw new GuliException(20001, "请先删除该章节下小节");
        }
        int delete = baseMapper.deleteById(id);
        return delete > 0;
    }

    @Override
    public boolean removeChapterByCourseId(String courseId) {
        QueryWrapper<EduChapter> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id", courseId);
        int delete = baseMapper.delete(wrapper);
        return delete > 0;
    }
}
